﻿using System;
using System.Collections.Generic;

namespace Platformer_Example.Controller.Input
{
    public class InputState
    {
        public enum Key
        {
            Up,
            Down,
            Left,
            Right,
            ButtonEast,
            ButtonWest,
            ButtonNorth,
            ButtonSouth,
            R1,
            R2,
            L1,
            L2,
            Start,
            Select,
            Invalid,
        }

        public delegate void OnKeyEventHandler(Key key);

        public event OnKeyEventHandler OnKeyPress;
        public event OnKeyEventHandler OnKeyRelease;

        public Dictionary<Key, bool> KeyState { get; private set; }

        /// <summary>
        /// Changes the state of a key to Pressed
        /// </summary>
        /// <param name="key">Key that was pressed</param>
        /// <returns>Returns true if the state changed</returns>
        public bool PressKey(Key key)
        {
            bool hasChanged = !KeyState[key];

            if (OnKeyPress != null && !KeyState[key])
                OnKeyPress(key);

            KeyState[key] = true;

            return hasChanged;
        }

        /// <summary>
        /// Changes the state of a key to Released
        /// </summary>
        /// <param name="key">Key that was pressed</param>
        /// <returns>Returns true if the state changed</returns>
        public bool ReleaseKey(Key key)
        {
            bool hasChanged = KeyState[key];

            if (OnKeyRelease != null && KeyState[key])
                OnKeyRelease(key);

            KeyState[key] = false;

            return hasChanged;
        }

        public InputState()
        {
            KeyState = new Dictionary<Key, bool>();

            foreach (var value in Enum.GetValues(typeof (Key)))
            {
                KeyState.Add((Key) value, false);
            }
        }
    }
}